import React from 'react'
import { inject, observer } from 'mobx-react';
import { withRouter,Route } from 'react-router-dom';
import { Button,Tools,Toast} from 'weaver-mobile';
import { RouteLayout,ListViewPage } from 'weaver-mobile-page';
import { Icon } from 'weaver-mobile';
import * as API from '../../api/fnaSpecial'
import * as mobx from 'mobx'
const getLabel = Tools.getLabel;

//注释 移动端解决特殊组件特殊显示的问题 
/**
 * 流程表单引入外部提供组件的问题 比如单内序号这个场景 
 * 1：外部明细和弹出卡片会分别渲染组件的不同对象 ，进去卡片的时候需要document拿到外部数据回写到卡片，如果修改了卡片里面的东西，需要手动使用document强行回显到外部
 * 2：弹出的卡片 当存在多个明细项 ：那么此时进行左右切换 这个时候不同卡片使用的是一个组件，那么这时候前面明细项的组件内的特殊数据会跑到后面明细项去。(因为是一个组件)
 *    解决办法：那么需要在render后面的componentDidUpdate周期将外部的数据回写到切换的卡片里面。（使用上暂时没发现问题）
 */

@inject('popupBillNumberStore')
@withRouter
@observer
export default class PopupBillNumberList extends React.Component {
  constructor(props) {
     super(props);
     this.state = {dnxhShowValue:""};
  }
  
  componentWillReceiveProps(nextProps) {

	}

	shouldComponentUpdate(nextProps, nextState) {
		return true;
  }

  componentDidUpdate() {
    /*
    *功能，在弹出卡片明细的进行左右切换的时候，将外部的明细单内序号取出，进行回填。
    *要放在render之后
    */
    /*
    const {rowIndex,fieldId} = this.props;
    let dnxhObj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanOut");
    let dnxhOutValue = '';
    if(!!dnxhObj){
      dnxhOutValue = dnxhObj.innerHTML;//拿到没有点击明细显示的单内序号
    }
    
    let obj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanInside");
    if(!!obj){
      document.getElementById("field"+fieldId+"_"+rowIndex+"spanInside").innerHTML = dnxhOutValue;//设置到点明细后弹出的表单，单内序号
    }
    */
	}

  
   componentDidMount() {
    const {fieldSet,fieldGet,rowIndex,fieldId,detailList,fieldObj,requestid,isDetailShow,detailType} = this.props;
    let lines =  window.WfForm.getDetailAllRowIndexStr(mobx.toJS(fieldObj).tableMark).split(",");//获取明细标的所有行号
    let detailKey = window.WfForm.getDetailRowKey("field"+fieldId+"_"+rowIndex);//获取明细表的主键
   
    //保存后或者新建提交到下个节点detailList有值
    if(detailList.length > 0 && requestid != "-1" && detailList[0]){
      //初始化单内序号在明细的展示
      if(isDetailShow){//外部     
        if(detailList[0][detailKey]){//如果是保存后再新建明细 外面的明细先建立这时候isDetailSho为true,这个时候detailKey是不存在的
          /*
          this.setState({
            dnxhShowValue: detailList[0][detailKey].dnxhShowName
          });
          */
        }
      } else {//将外部的回填到内部卡片单内序号
        /*
        let dnxhObj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanOut");
        let dnxhOutValue = '';
        if(!!dnxhObj){
          dnxhOutValue = dnxhObj.innerHTML;//拿到没有点击明细显示的单内序号
        }
        document.getElementById("field"+fieldId+"_"+rowIndex+"spanInside").innerHTML = dnxhOutValue;//设置到点明细后弹出的表单，单内序号
        */
      }

      //初始化明细后替换原明细数据
      if(detailType == 'borrow'){//借款
          let jklcReid =  window.WfForm.getFieldValue("field"+fieldGet[0]+"_"+rowIndex);
          let dnxh =  window.WfForm.getFieldValue("field"+fieldId+"_"+rowIndex);
          let mapkey = "borrowRequestIdInfo_"+jklcReid+"_"+dnxh;
          if(detailList[0][mapkey]){
            window.WfForm.changeFieldValue("field"+fieldSet[1]+"_"+rowIndex, {value: detailList[0][mapkey].jkje}); //借款金额
            window.WfForm.changeFieldValue("field"+fieldSet[2]+"_"+rowIndex, {value: detailList[0][mapkey].yhje});//已还金额
            window.WfForm.changeFieldValue("field"+fieldSet[3]+"_"+rowIndex, {value: detailList[0][mapkey].spzje});//审批中待还金额
            window.WfForm.changeFieldValue("field"+fieldSet[4]+"_"+rowIndex, {value: detailList[0][mapkey].whje});//未还金额
          }
      } else if(detailType == 'advance'){//预付款
          let YfklcReid = window.WfForm.getFieldValue("field"+fieldGet[0]+"_"+rowIndex);
          let dnxh = window.WfForm.getFieldValue("field"+fieldId+"_"+rowIndex);
          let mapkey = "advanceRequestIdInfo_"+YfklcReid+"_"+dnxh;

          if(detailList[0][mapkey]){
            window.WfForm.changeFieldValue("field"+fieldSet[1]+"_"+rowIndex, {value: detailList[0][mapkey].Yfkje}); //预付款金额
            window.WfForm.changeFieldValue("field"+fieldSet[2]+"_"+rowIndex, {value: detailList[0][mapkey].yhje});//已还金额
            window.WfForm.changeFieldValue("field"+fieldSet[3]+"_"+rowIndex, {value: detailList[0][mapkey].spzje});//审批中待还金额
            window.WfForm.changeFieldValue("field"+fieldSet[4]+"_"+rowIndex, {value: detailList[0][mapkey].whje});//未还金额
          }
      }
    } else {//新建的时候
        //将外部单内序号回填到弹出卡片的内部
        /*
        let dnxhObj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanOut");
        let dnxhOutValue = '';
        if(!!dnxhObj){
          dnxhOutValue = dnxhObj.innerHTML;//拿到没有点击明细显示的单内序号
        }
        
        let obj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanInside");
        if(!!obj){
          document.getElementById("field"+fieldId+"_"+rowIndex+"spanInside").innerHTML = dnxhOutValue;//设置到点明细后弹出的表单，单内序号
        }
        */
    }
    
   }
   
   render() {
    const { popupBillNumberStore,history,fnaSpecialStore }= this.props ;
    const { longList,list,template,loding }= popupBillNumberStore ;
    const { path,id } = fnaSpecialStore;

    //隐藏loding
    if(!loding){
      Toast.hide();
    }

    return (
      <div>      
        <div className={'fna-choose-item fna-choose-item-edit'}>
          {this.getShowHtml()}
        </div>
        <Route
          key={id}
          path={path}
          render={() => (
            <RouteLayout>
              <div
                key="popupList"
                className="wm-route-layout"
                style={{overflow:'auto','-webkit-overflow-scrolling':'touch'}}
              >
                <ListViewPage.Normal
                  store={longList}
                  heightSpace={47}
                  onRowClick={(selectedRowKeys) => {
                    this.writeback(selectedRowKeys);
                  }}
                />
              </div>
            </RouteLayout>
          )}
        />
      </div>
    );
  }

    //获取展示的组件
    getShowHtml = () => {
      const { showType,isDetailShow,viewAttr,rowIndex,fieldId,fieldObj,nodeType,dnxhValue,placeholder,isCardEdit } = this.props;
      const isDetail = mobx.toJS(fieldObj).tableMark.indexOf("detail_") > -1;
      const fieldMark = isDetail ? `field${fieldId}_${rowIndex}` : `field${fieldId}`;
      let component = [];
      let flag = this.getNodeType();
      const detailtype = mobx.toJS(fieldObj).detailtype;
      const swapClassName = `wf-req-input-item wf-input-${detailtype} wf-input-field${fieldId} ${viewAttr === 1 ? "wf-input-view" : "wf-input-edit"}`;
      //isDetailShow=true表示没有点击进入明细
      if(isDetailShow){//外部渲染
        if(!isCardEdit){
          component = [
            <div className="fna-choose-item-holder" onClick={flag?()=>{}:this.clickEvent}>
              <div className={swapClassName}>
                <div style={{color:'black'}}>{dnxhValue}</div>
                <input type="hidden" id={fieldMark} name={fieldMark} value={dnxhValue}/>
              </div>
              {!dnxhValue && <span>{getLabel(391001,'选择单内序号')}</span>}
            </div>,
            viewAttr === 3 && !dnxhValue && <div className="wf-choose-item-required">
                  <img src="/images/BacoError_wev9.png" align="absmiddle" />
            </div>,
            <div className="fna-choose-item-right" style={flag?{display:'none'}:{}}>
                <Icon type="right" />
            </div>
          ];
        } else {
          component = [
            <div className={swapClassName}>
              <div id={`${fieldMark}spanOut`}>{dnxhValue}</div>
              <div id={`${fieldMark}span`} className="fna-wf-input-view" style={{'display':'none'}} dangerouslySetInnerHTML={{__html:dnxhValue}}></div>
              <input type="hidden" id={fieldMark} name={fieldMark} value={dnxhValue}/>
            </div>
            ];
        }
      } else {//内部渲染
          component = [
              <div className="fna-choose-item-holder" onClick={flag?()=>{}:this.clickEvent}>
                <div className={swapClassName}>
                  <div id={`${fieldMark}spanInside`} style={{color:'black'}}>{dnxhValue}</div>
                  <div id={`${fieldMark}span`} className="fna-wf-input-view" style={{'display':'none'}} dangerouslySetInnerHTML={{__html:dnxhValue}}></div>
                  <input type="hidden" id={fieldMark} name={fieldMark} value={dnxhValue}/>
                </div>
                <span>{getLabel(391001,'选择单内序号')}</span>
              </div>,
              viewAttr === 3 && !dnxhValue && <div className="wf-choose-item-required">
                    <img src="/images/BacoError_wev9.png" align="absmiddle" />
              </div>,
              <div className="fna-choose-item-right" style={flag?{display:'none'}:{}}>
                  <Icon type="right" />
              </div>
          ];
      }
  
      return component;
    }
  
    //点击明细弹出表单后，不同的提交节点对用户展示不同的效果
    getNodeType = () => {
      const { nodeType,viewAttr } = this.props;

      return viewAttr == 1 && typeof(nodeType) !='undefined';
    }

    //获取按钮组
    getButton = () => {
      const { history }= this.props ;
      let buttonGroupData = [
        {
          key: 'submit',
          text: getLabel(826,'确定'),
          onClick: () => {history.go(-1);},
          type: 'primary'
        }
      ];
  
      return buttonGroupData;
    }

    //弹出单内序号的按钮
    clickEvent = () => {
      const { history,fnaSpecialStore,popupBillNumberStore,isDetailShow,detailType }= this.props ;
      const { rowIndex,requestid,fieldGet }= this.props ;
      const { queryDtlRowData_borrow,queryDtlRowData_advance }= popupBillNumberStore ;
      let lcId = window.WfForm.getFieldValue("field"+fieldGet[0]+"_"+rowIndex);
      let queryData = {};
      if(detailType == 'borrow'){
        queryData = {'requestid':requestid,'jklc':lcId};
        queryDtlRowData_borrow(queryData);
      } else if(detailType == 'advance'){
        queryData = {'requestid':requestid,'Yfklc':lcId};
        queryDtlRowData_advance(queryData);
      }
      history.push(fnaSpecialStore.path);
      //展示loding
      if(!isDetailShow){
        Toast.loading('Loading...', 5, () => {
        });
      }
    }

    //将选择的数据回写到明细
    writeback = (selectedRowKeys) => {
      const { history,fnaSpecialStore,detailType }= this.props ;
      let selectRecord = mobx.toJS(selectedRowKeys);
      const {fieldSet,requestid,fieldGet,rowIndex,fieldId} = this.props;
      let lcId = window.WfForm.getFieldValue("field"+fieldGet[0]+"_"+rowIndex);
      let dnxh = selectRecord.id;
      let typeId = selectRecord.typeId;//借款类型 
      let applicant = window.WfForm.getFieldValue("field"+fieldGet[1]);//申请人

      if(detailType == 'borrow'){//借款流程
          API.borrowInfoData({'requestid':requestid,'jklc':lcId,'dnxh':dnxh,'typeId':typeId,'applicant':applicant}).then(data =>{
            
            if(data.flag == true){
              window.WfForm.changeFieldValue("field"+fieldSet[0]+"_"+rowIndex, {value: data.requestmark}); //借款单号
              window.WfForm.changeFieldValue("field"+fieldSet[1]+"_"+rowIndex, {value: data.jkje}); //借款金额
              window.WfForm.changeFieldValue("field"+fieldSet[2]+"_"+rowIndex, {value: data.yhje});//已还金额
              window.WfForm.changeFieldValue("field"+fieldSet[3]+"_"+rowIndex, {value: data.spzje});//审批中待还金额
              window.WfForm.changeFieldValue("field"+fieldSet[4]+"_"+rowIndex, {value: data.whje});//未还金额

              window.WfForm.changeFieldValue("field"+fieldId+"_"+rowIndex, {value: dnxh});//单内序号 真id

              //设置到内部的单内序号
              /*
              this.setState({
                  dnxhShowValue:data.dnxhShowName //真序号
              });

              
              let dnxhObj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanOut");
              if(!!dnxhObj){
                dnxhObj.innerHTML=data.dnxhShowName;//将选择的单内序号条目设置到外部的单内序号
              }
              */
              history.go(-1);
            }
          });
      } else if(detailType == 'advance'){ //预付款流程
          API.advanceInfoData({'requestid':requestid,'Yfklc':lcId,'dnxh':dnxh,'typeId':typeId}).then(data =>{
            if(data.flag == true){
              window.WfForm.changeFieldValue("field"+fieldSet[0]+"_"+rowIndex, {value: data.requestmark}); //预付款单号
              window.WfForm.changeFieldValue("field"+fieldSet[1]+"_"+rowIndex, {value: data.Yfkje}); //预付款金额
              window.WfForm.changeFieldValue("field"+fieldSet[2]+"_"+rowIndex, {value: data.yhje});//已还金额
              window.WfForm.changeFieldValue("field"+fieldSet[3]+"_"+rowIndex, {value: data.spzje});//审批中待还金额
              window.WfForm.changeFieldValue("field"+fieldSet[4]+"_"+rowIndex, {value: data.whje});//未还金额

              window.WfForm.changeFieldValue("field"+fieldId+"_"+rowIndex, {value: dnxh});//单内序号
              
              //设置到内部的单内序号
              /*
              this.setState({
                dnxhShowValue:data.dnxhShowName //真序号
              });

              
              let dnxhObj = document.getElementById("field"+fieldId+"_"+rowIndex+"spanOut");
              if(!!dnxhObj){
                dnxhObj.innerHTML=data.dnxhShowName;//将选择的单内序号条目设置到外部的单内序号
              }
              */
              history.go(-1);
            }
        });
      }
    }
}